var modifyOrAddFlag;

$(document)
		.ready(
				function() {
					$('#win').window('close');

					// 接口状态下拉框
					$('#comboxIsEnable').combobox(
							{
								url : BASE_URL_DATA_DICTIONARY_VALUE_SEARCH
										+ '/findByTypeCode?typeCode='
										+ DDTC_TOKEN_STATUS + '&v='
										+ Math.random(),
								valueField : 'valueCode',
								textField : 'valueName',
								editable : false,
								method : 'get',
								loadFilter : function(data) {
									var allCheck = {
										'valueCode' : '',
										'valueName' : '全部'
									};
									data.unshift(allCheck);
									return data;
								}
							});

					$('#comboxPubField')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '请选择'
											};
											if (data.content) {
												data.content.unshift(allCheck);
											} else {
												return data;
											}
											return data.content;
										},
										onSelect : function(record) {
											comboxPubSystem
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {

																	var allCheck = {
																		'id' : '',
																		'name' : '请选择'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onSelect : function(
																		record) {
																	/*
																	 * comboxInterface
																	 * .combobox({
																	 * disabled :
																	 * false,
																	 * method :
																	 * 'get',
																	 * queryParams : {
																	 * fieldSystemId :
																	 * record.id },
																	 * url :
																	 * BASE_URL_SYSTEM_INTERFACE_SEARCH +
																	 * '/findByOwnerFieldSystem_Id' +
																	 * '?v=' +
																	 * Math
																	 * .random(),
																	 * valueField :
																	 * 'id',
																	 * textField :
																	 * 'jobName',
																	 * data :
																	 * '',
																	 * loadFilter :
																	 * function(
																	 * data) {
																	 * if
																	 * (data[0].id ==
																	 * "") {
																	 * return
																	 * data; }
																	 * var
																	 * allCheck = {
																	 * 'id' :
																	 * '',
																	 * 'jobName' :
																	 * '请选择' };
																	 * data.unshift(allCheck);
																	 * return
																	 * data; },
																	 * onLoadSuccess :
																	 * function() { $(
																	 * '#comboxInterface')
																	 * .combobox(
																	 * 'setValue',
																	 * ''); }
																	 * });
																	 */
																},
																onLoadSuccess : function() {
																	$(
																			'#comboxInterface')
																			.combobox(
																					'setValue',
																					'');

																},
															// onChange :
															// function(
															// newValue,
															// oldValue) {
															// $(
															// '#datagrid4if')
															// .datagrid(
															// 'reload');
															// }
															}).load();
											/*
											 * comboxInterface.combobox({
											 * disabled : true, valueField :
											 * 'id', textField : 'jobName',
											 * editable : false, url : '', data :
											 * [], loadFilter : function(data) {
											 * var allCheck = { id : '', jobName :
											 * '请选择', 'selected' : 'true' };
											 * data.unshift(allCheck); return
											 * data; } });
											 */
										},

									});

					var comboxPubSystem = $('#comboxPubSystem').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'name',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								name : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}

					});
					$('#comboxCallField')
							.combobox(
									{
										url : BASE_URL_FIELD_SEARCH
												+ '/findAllOfCurrentUserCanManage'
												+ '?v=' + Math.random(),
										valueField : 'id',
										textField : 'name',
										editable : false,
										method : 'get',
										loadFilter : function(data) {
											var allCheck = {
												'id' : '',
												'name' : '请选择'
											};
											if (data.content) {
												data.content.unshift(allCheck);
											} else {
												return data;
											}
											return data.content;
										},
										onSelect : function(record) {
											comboxCallSystem
													.combobox(
															{
																disabled : false,
																method : 'get',
																queryParams : {
																	fieldId : record.id
																},
																url : BASE_URL_FIELD_SYSTEM_SEARCH
																		+ '/findByFieldOfCurrentUserCanManage'
																		+ '?v='
																		+ Math
																				.random(),
																valueField : 'id',
																textField : 'name',
																data : '',
																loadFilter : function(
																		data) {

																	var allCheck = {
																		'id' : '',
																		'name' : '请选择'
																	};
																	data.content
																			.unshift(allCheck);
																	return data.content;
																},
																onSelect : function(
																		record) {
																	/*
																	 * comboxInterface4Call
																	 * .combobox({
																	 * disabled :
																	 * false,
																	 * method :
																	 * 'get',
																	 * queryParams : {
																	 * fieldSystemId :
																	 * record.id },
																	 * url :
																	 * BASE_URL_SYSTEM_INTERFACE_SEARCH +
																	 * '/findByOwnerFieldSystem_Id' +
																	 * '?v=' +
																	 * Math
																	 * .random(),
																	 * valueField :
																	 * 'id',
																	 * textField :
																	 * 'jobName',
																	 * data :
																	 * '',
																	 * loadFilter :
																	 * function(
																	 * data) {
																	 * if
																	 * (data[0].id ==
																	 * "") {
																	 * return
																	 * data; }
																	 * var
																	 * allCheck = {
																	 * 'id' :
																	 * '',
																	 * 'jobName' :
																	 * '请选择' };
																	 * data
																	 * .unshift(allCheck);
																	 * return
																	 * data; },
																	 * onLoadSuccess :
																	 * function() { $(
																	 * '#comboxInterface')
																	 * .combobox(
																	 * 'setValue',
																	 * ''); }
																	 * });
																	 */
																},
																onLoadSuccess : function() {
																	$(
																			'#comboxInterface')
																			.combobox(
																					'setValue',
																					'');

																}
															}).load();
											/*
											 * comboxInterface4Call.combobox({
											 * disabled : true, valueField :
											 * 'id', textField : 'jobName',
											 * editable : false, url : '', data :
											 * [], loadFilter : function(data) {
											 * var allCheck = { id : '', jobName :
											 * '请选择', 'selected' : 'true' };
											 * data.unshift(allCheck); return
											 * data; } });
											 */
										}

									});

					var comboxCallSystem = $('#comboxCallSystem').combobox({
						disabled : true,
						valueField : 'id',
						textField : 'name',
						editable : false,
						url : '',
						data : [],
						loadFilter : function(data) {
							var allCheck = {
								id : '',
								name : '请选择',
								'selected' : 'true'
							};
							data.unshift(allCheck);
							return data;
						}

					});

					$("#datagrid")
							.datagrid(
									{
										url : BASE_URL_API
												+ '/serviceAccessManagement/findInterfaceTokenInfos?v='
												+ Math.random(),
										method : 'get',
										autoRowHeight : true,
										singleSelect : true,
										striped : true,
										nowrap : false,
										pageSize : 20,
										pageList : [ 10, 20, 50, 100 ],
										columns : [ [
												{
													field : 'interfacePubSystemName',
													title : '发布方系统',
													width : 30,
													align : 'center'
												},
												{
													field : 'interfaceName',
													title : '接口名称',
													width : 50,
													align : 'center'
												},

												{
													field : 'interfaceCallSytemName',
													title : '调用方系统',
													width : 30,
													align : 'center'
												},
												{
													field : 'applyUserCode',
													title : '申请账号',
													width : 20,
													align : 'center'
												},
												{
													field : 'appKey',
													title : '密钥',
													width : 40,
													align : 'center'
												},
												{
													field : 'status',
													title : '状态',
													width : 15,
													formatter : function(value,
															rowData, rowIndex) {
														return value == '0' ? "未生效"
																: (value == '1' ? '生效'
																		: '已过期');
													}
												},
												{
													field : 'applyDateStr',
													title : '申请时间',
													width : 30,
													align : 'center'
												},
												{
													field : 'keyInvalidDateStr',
													title : '过期时间',
													width : 30,
													align : 'center'
												},
												{
													field : 'bu',
													title : '操作',
													width : 22,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														if (rowData.status == '1') {
															return '<a href="javascript:void(0)" class="default_btn fl"  onclick="setDisable('
																	+ rowIndex
																	+ ')">停用</a><a href="javascript:void(0)" class="default_btn fl"   onclick="changeKeyInvalidDate('
																	+ rowIndex
																	+ ')">修改有效期</a>';
														}

														if (rowData.status == '2') {
															return '<a href="javascript:void(0)"  class="default_btn fl"  onclick="changeKeyInvalidDate('
																	+ rowIndex
																	+ ')">修改有效期</a>';
														}
														return '<a href="javascript:void(0)" class="default_btn fl"  onclick="setEnable('

																+ rowIndex
																+ ')">启用</a><a href="javascript:void(0)" class="default_btn fl" onclick="changeKeyInvalidDate('
																+ rowIndex
																+ ')">修改有效期</a>';
													}
												} ] ],
										pagination : true,
										onSelect : function(rowIndex, rowData) {
											if (rowData.runStatusForDisplay == "暂停") {
												$(".startOrStop .l-btn-text")
														.text("重启");
												$(".startOrStop .icon-more")
														.css("background",
																"url(../../images/icons/restart.png) no-repeat center center");
											} else if (rowData.runStatusForDisplay == "正常") {
												$(".startOrStop .l-btn-text")
														.text("暂停");
												$(".startOrStop .icon-more")
														.css("background",
																"url(../../images/icons/stop.png) no-repeat center center");
											}
											$("#toolbar_edit").linkbutton(
													'enable');
											$("#toolbar_delete").linkbutton(
													'enable');
										},
										onUnselect : function() {
											$(".startOrStop .l-btn-text").text(
													"暂停/重启");
											$(".startOrStop .icon-more")
													.css("background",
															"url(../../images/icons/more.png) no-repeat center center");
										},
										loadFilter : function(data) {
											// alert("inData:"
											// + JSON.stringify(data));
											return {
												total : data.totalElements,
												rows : data.content
											};
										},
										onBeforeLoad : function(param) {
											param.page -= 1;
											param.size = param.rows;
											delete param.rows;

											param.sort = 'createTime,desc';

											var interfaceName = $('#txtIfName')
													.val();
											if (interfaceName != "") {
												param.interfaceName = interfaceName;
											}
											var pubFieldId = $(
													'#comboxPubField')
													.combobox('getValue');
											if (pubFieldId != "") {
												param.pubFieldId = pubFieldId;
											}
											var pubSystemId = $(
													'#comboxPubSystem')
													.combobox('getValue');
											if (pubSystemId != "") {
												param.pubSystemId = pubSystemId;
											}
											var callFieldId = $(
													'#comboxCallField')
													.combobox('getValue');
											if (callFieldId != "") {
												param.callFieldId = callFieldId;
											}
											var callSystemId = $(
													'#comboxCallSystem')
													.combobox('getValue');
											if (callSystemId != "") {
												param.callSystemId = callSystemId;
											}
											var status = $('#comboxIsEnable')
													.combobox('getValue');
											if (status != "") {
												param.status = status;
											}
											var appUserCode = $(
													'#txtAppUserCode').val();
											if (appUserCode != "") {
												param.appUserCode = appUserCode;
											}
											var appStartDate = $(
													"#txtAppStartDateTime")
													.datebox('getValue');
											if (appStartDate != "") {
												param.appStartDate = appStartDate;
											}
											var appEndDate = $(
													"#txtAppEndDateTime")
													.datebox('getValue');
											if (appEndDate != "") {
												param.appEndDate = appEndDate;
											}
										}
									});

					$("#datagrid").datagrid('getPager').pagination({
						displayMsg : '当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
					});
					$(".panel-tool-close, #instance_cancel").click(function(e) {
						$("body").css("overflow-x", "inherit")
					});

				});

// 查询
function search() {
	$('#datagrid').datagrid('reload');
}
function refresh() {
	$('#datagrid').datagrid('reload');
}

// 停用
function setDisable(index) {
	updateStatus(index, '0');
}
// 启用
function setEnable(index) {
	var row = $('#datagrid').datagrid('getData').rows[index];
	var now = new Date();
	var expire = new Date(row.keyInvalidDateStr);
	if (expire < now) {
		$.messager.alert('警告', "密钥已过期，不能启用！", "warning");
		return;
	}
	updateStatus(index, '1');
}
function updateStatus(index, status) {
	var msg = "停用";
	if (status == '1') {
		msg = "启用";
	}
	var row = $('#datagrid').datagrid('getData').rows[index];
	// alert("inData:"+JSON.stringify(row));
	var id = row.tokenId;
	var data = {
		id : id,
		status : status
	};
	$("#progressbar, #progressbar_tips").fadeIn();
	loading_point.timer = setInterval(loading, 200);
	$.ajax({
		type : "get",
		url : BASE_URL_API + '/serviceAccessManagement/updateStatus?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			if (data.result == true) {
				$.messager.alert('提示', "<p>" + msg + "成功!</p>", 'info',
						function() {
							refresh();
						});
			} else {
				$.messager.alert('错误', '<p>服务异常，' + msg + '失败，' + data.msg
						+ '!</p>', 'error');
			}

		},
		error : function() {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			$.messager.alert('错误', '<p>服务异常，' + msg + '失败，请稍后重试或联系管理员!</p>',
					'error');
		}
	});
}
function changeKeyInvalidDate(rowIndex) {
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	$('#tokenId').val(row.tokenId);
	$('#applyDate').val(row.applyDateStr);
	$('#win').window('setTitle', '服务系统有效期控制');
	$('#win').window('open');
}
function saveKeyInvalidDate() {
	var tokenId = $('#tokenId').val();
	var applyDate = $('#applyDate').val();
	var date = $("#txtKeyInvalidDate").datebox('getValue');
	if (date == null || date == '') {
		$.messager.alert('警告', '<p>失效时间不能为空!</p>', "warning");
		return;
	}
	if (applyDate > date) {
		$.messager.alert('警告', '<p>过期时间不能在申请时间之前!</p>', "warning");
		return;
	}
	data = {
		id : tokenId,
		date : date
	};
	$.ajax({
		type : "get",
		url : BASE_URL_API + '/serviceAccessManagement/updateKeyInvalidDate?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			if (data.result == true) {
				$('#win').window('close');
				$.messager.alert('提示', "<p>修改失效时间成功!</p>", 'info', function() {
					refresh();
				});
			} else {
				$.messager.alert('错误', '<p>服务异常，' + data.msg
						+ '请稍后重试或联系管理员!</p>', 'error');
			}

		},
		error : function() {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			$.messager.alert('错误', '<p>服务异常，更新密钥失效期失败，请稍后重试或联系管理员!</p>',
					'error');
		}
	});
}
function cancel() {
	$('#win').window('close');
}
var loading_point = {
	timer : null,
	len : 3,
	count : 0
};
function loading() {
	if (loading_point.count < loading_point.len) {
		loading_point.count++;
		$("#progressbar_point").text($("#progressbar_point").text() + ".");
	} else {
		loading_point.count = 0;
		$("#progressbar_point").text("");
	}
}
